package com.example.xinhuazidian.utils

import android.app.ProgressDialog
import android.content.Context
import android.text.TextUtils
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.StringRes
import com.example.xinhuazidian.R

class LoadingDialog @JvmOverloads constructor(context: Context?, msg: CharSequence? = "") : ProgressDialog(context, R.style.LoadingDialogStyle) {

    var mLoadingTextView: TextView
    var mView: View = View.inflate(context, R.layout.dialog_loading, null)

    /**
     * 这里的Context 必须用actiivty 不能用applicationContext
     */
    init {
        mLoadingTextView = mView.findViewById<View>(R.id.mLoadingTextView) as TextView
        if (!TextUtils.isEmpty(msg)) {
            mLoadingTextView.text = msg
            mLoadingTextView.visibility = View.VISIBLE
        } else {
            mLoadingTextView.visibility = View.GONE
        }
        this.setCanceledOnTouchOutside(false)
        this.setCancelable(true)
    }

    override fun show() {
        try {
            if (this.isShowing) {
                this.dismiss()
            } else {
                super.show()
            }
            //setContentView（）一定要在show之后调用
            this.setContentView(mView)
        } catch (_: WindowManager.BadTokenException) {
        }
    }

    fun setMessage(message: String?) {
        if (!TextUtils.isEmpty(message)) {
            if (mLoadingTextView.visibility != View.VISIBLE) {
                mLoadingTextView.visibility = View.VISIBLE
            }
            mLoadingTextView.text = message
        } else {
            if (mLoadingTextView.visibility == View.VISIBLE) {
                mLoadingTextView.visibility = View.GONE
            }
        }
    }

    fun setMessage(@StringRes message: Int) {
        if (mLoadingTextView.visibility != View.VISIBLE) {
            mLoadingTextView.visibility = View.VISIBLE
        }
        mLoadingTextView.setText(message)
    }
}